package com.ssy.lingxi.system.service.impl;

import com.ssy.lingxi.common.constant.basic.*;
import com.ssy.lingxi.common.constant.contract.ContractSourceTypeEnum;
import com.ssy.lingxi.common.constant.marketing.ActivityTypeEnum;
import com.ssy.lingxi.common.constant.member.MemberLevelTypeEnum;
import com.ssy.lingxi.common.constant.order.*;
import com.ssy.lingxi.common.constant.pay.BalanceTypeEnum;
import com.ssy.lingxi.common.constant.settle.SettlementTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.member.merchant.api.constant.*;
import com.ssy.lingxi.member.merchant.api.model.constant.MemberProcessTypeEnum;
import com.ssy.lingxi.system.dao.*;
import com.ssy.lingxi.system.entity.*;
import com.ssy.lingxi.system.service.ISystemDataInitService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 系统启动时，初始化数据
 * @author 万宁
 * @version 2.0.0
 * @date 2021-06-06
 */
@Service
public class SystemDataInitServiceImpl implements ISystemDataInitService {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private BasePlatformProcessRepository basePlatformProcessRepository;

    @Resource
    private MiddlegroundUserRepository middlegroundUserRepository;

    @Resource
    private LoginPatternRepository loginPatternRepository;

    @Resource
    private RoleRepository roleRepository;

    @Resource
    private MemberEquitiesRepository memberEquitiesRepository;
    
    @Resource
    private MemberPromotionRuleRepository memberPromotionRuleRepository;

    @Resource
    private CreditIndexRepository creditIndexRepository;

    @Resource
    private RuleConfigurationRepository ruleConfigurationRepository;

    @Resource
    private PayWayRepository payWayRepository;

    @Resource
    private ContractParamRepository contractParamRepository;

    @Resource
    private CurrencyRepository currencyRepository;

    @Resource
    private LanguageRepository languageRepository;

    @Resource
    private CountryAreaRepository countryAreaRepository;

    /**
     * 初始化数据
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public void initSystemData() {
        //初始化平台会员审核流程（会员注册流程）
        initBasePlatformProcess();

        //系统管理员 admin 账号
        initAdmin();

        //登录模式
        initLoginPattern();

        //语言
        initLanguage();

        //货币设置
        initCurrency();

        //国家区域
        initCountryArea();

        //创建“平台”会员角色
        initPlatformRole();

        //会员基础权益
        initMemberEquities();
        
        //会员基础升级规则
        initMemberPromotionRule();

        //会员基础信用
        initCreditIndex();

        //平台规则配置
        initRuleConfiguration();

        //支付方式
        initPayWay();

        //电子合同参数
        initContractParam();
    }

    /**
     * 初始化平台会员审核流程（会员注册流程）
     */
    private void initBasePlatformProcess() {
        List<BasePlatformProcess> platformProcesses = new ArrayList<>();
        BasePlatformProcess processDO = new BasePlatformProcess();
        processDO.setProcessName("会员注册--无需审核");
        processDO.setProcessType(MemberProcessTypeEnum.PLATFORM_VALIDATION.getCode());
        processDO.setProcessKey("platform_member_directly");
        processDO.setDescription("1-申请注册");
        platformProcesses.add(processDO);

        processDO = new BasePlatformProcess();
        processDO.setProcessName("会员注册--确认会员资料");
        processDO.setProcessType(MemberProcessTypeEnum.PLATFORM_VALIDATION.getCode());
        processDO.setProcessKey("platform_member_verify_confirm");
        processDO.setDescription("1-申请注册-->2-确认会员资料");
        platformProcesses.add(processDO);

        processDO = new BasePlatformProcess();
        processDO.setProcessName("会员注册--全审核流程");
        processDO.setProcessType(MemberProcessTypeEnum.PLATFORM_VALIDATION.getCode());
        processDO.setProcessKey("platform_member_verify");
        processDO.setDescription("1-申请注册-->2-提交审核-->3-审核(一级)-->4-审核(二级)-->5-确认会员资料");
        platformProcesses.add(processDO);

        List<BasePlatformProcess> basePlatformProcesses = basePlatformProcessRepository.findAll();
        basePlatformProcesses.forEach(process -> platformProcesses.stream().filter(p -> p.getProcessKey().equals(process.getProcessKey())).findFirst().ifPresent(p -> {
            process.setProcessName(p.getProcessName());
            process.setDescription(p.getDescription());
            process.setProcessType(p.getProcessType());
        }));

        basePlatformProcesses.addAll(platformProcesses.stream().filter(p -> basePlatformProcesses.stream().noneMatch(tp -> tp.getProcessKey().equals(p.getProcessKey()))).collect(Collectors.toList()));
        basePlatformProcessRepository.saveAll(basePlatformProcesses);
    }

    /**
     * 初始化系统管理员
     */
    private void initAdmin() {
        if(countTable("cf_middleground_user") > 0) {
            return;
        }

        alterSequence("cf_middleground_user_seq");

        MiddlegroundUser user = new MiddlegroundUser();
        user.setAccount("admin");
        user.setName("超级管理员");
        user.setState(1);
        user.setTel("");
        user.setPassword("FED6E4F466C605760292A23FC39E0B8F");
        user.setFinallyLoginTime(System.currentTimeMillis());
        user.setEmail("");
        user.setAddress("");
        user.setIdentityCard("");
        user.setPost("超级管理员");
        user.setUpdateTime(System.currentTimeMillis());
        user.setCreateTime(System.currentTimeMillis());
        user.setCreateRole(1L);
        middlegroundUserRepository.saveAndFlush(user);
    }

    /**
     * 初始化“平台”角色
     */
    private void initPlatformRole() {
        if(countTable("cf_role") > 0) {
            return;
        }

        Role role = new Role();
        role.setId(1L);
        role.setCreateTime(System.currentTimeMillis());
        role.setName("平台");
        role.setServiceType("平台运营");
        role.setCode("");
        role.setCreateRole(1L);
        role.setRoleType(1);
        role.setMemberType(1);
        role.setState(1);
        role.setUpdateTime(System.currentTimeMillis());
        role.setDescribed("系统内置平台后台角色");

        roleRepository.saveAndFlush(role);
    }

    /**
     * 初始化语言设置
     */
    private void initLanguage() {
        if(countTable("cf_language") > 0) {
            return;
        }

        alterSequence("cf_language_seq");

        Language language = new Language();
        language.setCreateRoleId(1L);
        language.setCreateTime(System.currentTimeMillis());
        language.setName("中文");
        language.setNameEn("China");
        language.setState(1);
        language.setUpdateTime(System.currentTimeMillis());
        language.setImgUrl("");
        languageRepository.saveAndFlush(language);
    }

    /**
     * 初始化货币设置
     */
    private void initCurrency() {
        if(countTable("cf_currency") > 0) {
            return;
        }

        alterSequence("cf_currency_seq");

        Currency currency = new Currency();
        currency.setCreateRoleId(1L);
        currency.setCreateTime(System.currentTimeMillis());
        currency.setNameEn("RMB");
        currency.setName("人民币");
        currency.setShortenedForm("");
        currency.setSymbol("￥");
        currency.setImgUrl("");
        currency.setState(1);
        currency.setUpdateTime(System.currentTimeMillis());
        currencyRepository.saveAndFlush(currency);
    }

    /**
     * 初始化国家区域设置
     */
    private void initCountryArea() {
        if(countTable("cf_country_area") > 0) {
            return;
        }

        alterSequence("cf_country_area_seq");

        CountryArea area = new CountryArea();
        area.setCode(String.valueOf(CountryCodeEnum.China.getTypeEnum()));
        area.setCreateRoleId(1L);
        area.setCreateTime(System.currentTimeMillis());
        area.setName(CountryCodeEnum.China.getCn());
        area.setNameEn(CountryCodeEnum.China.getEn());
        Currency currency = currencyRepository.findFirstByName("人民币");
        area.setCurrencyId(currency == null ? 1 : currency.getId());
        Language language = languageRepository.findFirstByName("中文");
        area.setLanguageId(language == null ? 1 : language.getId());
        area.setTelCode(CountryCodeEnum.China.getCode());
        area.setTelNumber(11);
        area.setState(1);
        area.setImgUrl("");
        area.setUpdateTime(System.currentTimeMillis());
        countryAreaRepository.saveAndFlush(area);
    }

    /**
     * 登录模式
     */
    private void initLoginPattern() {
        if(countTable("cf_login_pattern") > 0) {
            return;
        }

        alterSequence("cf_login_pattern_seq");

        LoginPattern pattern = new LoginPattern();
        pattern.setLoginDefaul(0);
        pattern.setWxEwm(0);
        pattern.setWxVerify(0);
        pattern.setQqVerify(0);
        pattern.setAlipayVerify(0);
        pattern.setAnewLogin(0);
        pattern.setLoginStart(0);
        pattern.setAllowBrowse(0);
        pattern.setPlatformAnewLogin(0);
        pattern.setPlatformLoginStart(0);
        pattern.setPlatformLoginDefaul(0);
        pattern.setMiddlegroundAnewLogin(0);
        pattern.setMiddlegroundLoginStart(0);
        pattern.setMiddlegroundLoginDefaul(0);
        pattern.setCreateTime(System.currentTimeMillis());
        pattern.setUpdateTime(System.currentTimeMillis());
        loginPatternRepository.saveAndFlush(pattern);
    }

    /**
     * 会员基础权益
     */
    private void initMemberEquities() {
        if(countTable("cf_member_equities") > 0) {
            return;
        }

        alterSequence("cf_member_equities_seq");

        List<MemberEquities> equities = new ArrayList<>();
        for (MemberRightTypeEnum rightTypeEnum : MemberRightTypeEnum.values()) {
            MemberEquities equity = new MemberEquities();
            equity.setEquitiesExplain(rightTypeEnum.getRemark());
            equity.setEquitiesManner(MemberRightAcquireWayEnum.ACQUIRE_BY_TRADE.getMessage());
            equity.setEquitiesName(rightTypeEnum.getMessage());
            equity.setTypeEnum(rightTypeEnum.getCode());
            equity.setParameterManner(MemberRightParamWayEnum.SET_BY_TRADE_PRICE_RATE.getMessage());
            equities.add(equity);
        }

        memberEquitiesRepository.saveAll(equities);
    }

    /**
     * 会员基础升级规则
     */
    private void initMemberPromotionRule() {
        if(countTable("cf_member_promotion_rule") > 0) {
            return;
        }

        alterSequence("cf_member_promotion_rule_seq");

        List<MemberPromotionRule> ruleList = new ArrayList<>();

        for (MemberLevelTypeEnum memberLevelTypeEnum : MemberLevelTypeEnum.values()) {
            for (MemberLevelRuleTypeEnum ruleTypeEnum : MemberLevelRuleTypeEnum.values()) {
                MemberPromotionRule rule = new MemberPromotionRule();
                rule.setCreateRoleId(1L);
                rule.setCreateTime(System.currentTimeMillis());
                rule.setType(memberLevelTypeEnum.getCode());
                rule.setPromotionRule(ruleTypeEnum.getCode());
                rule.setExplain(ruleTypeEnum.getRemark());
                rule.setState(1);
                rule.setUpdateTime(System.currentTimeMillis());
                ruleList.add(rule);
            }
        }

        memberPromotionRuleRepository.saveAll(ruleList);
    }

    /**
     * 会员基础信用
     */
    private void initCreditIndex() {
        if(countTable("cf_credit_index") > 0) {
            return;
        }
        
        alterSequence("cf_credit_index_seq");

        List<CreditIndex> indices = new ArrayList<>();
        for (MemberCreditTypeEnum creditTypeEnum : MemberCreditTypeEnum.values()) {
            CreditIndex index = new CreditIndex();
            index.setCreateRoleId(1L);
            index.setCreateTime(System.currentTimeMillis());
            index.setUpdateTime(System.currentTimeMillis());
            index.setState(1);
            index.setProject(creditTypeEnum.getName());
            index.setExplain(creditTypeEnum.getRemark());
            index.setWeight(creditTypeEnum.getDefaultPoint());
            index.setTypeEnum(creditTypeEnum.getCode());
            indices.add(index);
        }

        creditIndexRepository.saveAll(indices);
    }

    /**
     * 平台规则配置
     */
    private void initRuleConfiguration() {
        List<RuleConfiguration> ruleList = new ArrayList<>();
        //资金归集模式
        ruleList.addAll(Arrays.stream(FundModeEnum.values()).sorted(Comparator.comparingInt(FundModeEnum::getCode)).map(fundModeEnum ->
                new RuleConfiguration(1, PlatformRuleTypeEnum.FUND.getCode(),fundModeEnum.getName(),"资金归集模式", fundModeEnum.getCode())
        ).collect(Collectors.toList()));

        //库存扣减策略
        ruleList.addAll(Arrays.stream(InventoryReduceTypeEnum.values()).sorted(Comparator.comparingInt(InventoryReduceTypeEnum::getCode)).map(inventoryReduceTypeEnum ->
                new RuleConfiguration(1, PlatformRuleTypeEnum.INVENTORY.getCode(),inventoryReduceTypeEnum.getName(),"库存扣减策略", inventoryReduceTypeEnum.getCode())
        ).collect(Collectors.toList()));

        //订单模式
        ruleList.addAll(Arrays.stream(OrderModeEnum.values()).sorted(Comparator.comparingInt(OrderModeEnum::getCode)).map(orderMode ->
            new RuleConfiguration(1, PlatformRuleTypeEnum.ORDER_MODE.getCode(),orderMode.getName(),"下单模式", orderMode.getCode())
        ).collect(Collectors.toList()));

        //订单类型
        ruleList.addAll(Arrays.stream(OrderTypeEnum.values()).sorted(Comparator.comparingInt(OrderTypeEnum::getCode)).map(orderType ->
                        new RuleConfiguration(1,PlatformRuleTypeEnum.ORDER_TYPE.getCode(), orderType.getName(),"订单类型", orderType.getCode())
                ).collect(Collectors.toList()));

        //营销活动类型
        ruleList.addAll(Arrays.stream(ActivityTypeEnum.values()).filter(e -> !e.getCode().equals(0)).sorted(Comparator.comparingInt(ActivityTypeEnum::getCode)).map(activityType ->
                new RuleConfiguration(1,PlatformRuleTypeEnum.MARKETING.getCode(), activityType.getMessage(),"营销活动类型", activityType.getCode())
        ).collect(Collectors.toList()));

        //结算方式
        ruleList.addAll(Arrays.stream(OrderSettlementEnum.values()).sorted(Comparator.comparingInt(OrderSettlementEnum::getCode)).map(settlement ->
                new RuleConfiguration(1,PlatformRuleTypeEnum.SETTLEMENT.getCode(), settlement.getName(),"结算方式", settlement.getCode())
        ).collect(Collectors.toList()));

        //品类与属性使用方式
        ruleList.addAll(Arrays.stream(OrderCatetoryAttributeEnum.values()).sorted(Comparator.comparingInt(OrderCatetoryAttributeEnum::getCode)).map(attributeEnum ->
                new RuleConfiguration(1,PlatformRuleTypeEnum.PRODUCT_CATEGORY.getCode(), attributeEnum.getName(),"品类与属性使用方式", attributeEnum.getCode())
        ).collect(Collectors.toList()));

        //采购询源类型
        ruleList.addAll(Arrays.stream(ContractSourceTypeEnum.values()).filter(e -> !e.getCode().equals(0)).sorted(Comparator.comparingInt(ContractSourceTypeEnum::getCode)).map(sourceTypeEnum ->
                new RuleConfiguration(1,PlatformRuleTypeEnum.PURCHASE_SOURCE.getCode(), sourceTypeEnum.getName(),"采购寻源类型", sourceTypeEnum.getCode())
        ).collect(Collectors.toList()));

        //采购合同付款方式
        ruleList.addAll(Arrays.stream(PurchaseContractPayTypeEnum.values()).sorted(Comparator.comparingInt(PurchaseContractPayTypeEnum::getCode)).map(contractPayTypeEnum ->
                new RuleConfiguration(1,PlatformRuleTypeEnum.PURCHASE_CONTRACT.getCode(), contractPayTypeEnum.getName(),"采购合同付款方式", contractPayTypeEnum.getCode())
        ).collect(Collectors.toList()));

        //结算支付方式
        ruleList.addAll(Arrays.stream(SettlementTypeEnum.values()).sorted(Comparator.comparingInt(SettlementTypeEnum::getCode)).map(settlementTypeEnum ->
                new RuleConfiguration(1,PlatformRuleTypeEnum.SETTLEMENT_TYPE.getCode(), settlementTypeEnum.getName(),PlatformRuleTypeEnum.SETTLEMENT_TYPE.getName(), settlementTypeEnum.getCode())
        ).collect(Collectors.toList()));


        //账户余额类型
        ruleList.addAll(Arrays.stream(BalanceTypeEnum.values()).sorted(Comparator.comparingInt(BalanceTypeEnum::getCode)).map(balanceTypeEnum ->
            new RuleConfiguration(1, PlatformRuleTypeEnum.BALANCE_TYPE.getCode(), balanceTypeEnum.getName(), PlatformRuleTypeEnum.BALANCE_TYPE.getName(), balanceTypeEnum.getCode())
        ).collect(Collectors.toList()));

        List<RuleConfiguration> configs = ruleConfigurationRepository.findAll();
        configs.forEach(config -> ruleList.stream().filter(r -> r.getPlatformType().equals(config.getPlatformType()) && r.getCode().equals(config.getCode())).findFirst().ifPresent(r -> {
            config.setIsPitchOn(r.getIsPitchOn());
            config.setPlatformTypeName(r.getPlatformTypeName());
            config.setPlatformWayName(r.getPlatformWayName());
        }));

        configs.addAll(ruleList.stream().filter(r -> configs.stream().noneMatch(config -> config.getPlatformType().equals(r.getPlatformType()) && config.getCode().equals(r.getCode()))).collect(Collectors.toList()));
        ruleConfigurationRepository.saveAll(configs);
    }

    /**
     * 支付参数
     */
    private void initPayWay() {
        if(countTable("cf_pay_way") == 0) {
            alterSequence("cf_pay_way_seq");
        }

        List<OrderPayTypeEnum> payTypeEnums = Arrays.stream(OrderPayTypeEnum.values()).filter(OrderPayTypeEnum::getUseForPaymentSetting).sorted(Comparator.comparingInt(OrderPayTypeEnum::getCode)).collect(Collectors.toList());
        List<PayWay> payWayList = payTypeEnums.stream().flatMap(payType -> payType.getPayChannels().stream().sorted(Comparator.comparingInt(OrderPayChannelEnum::getCode)).map(payChannel -> {
            PayWay payWay = new PayWay();
            payWay.setPayType(payType.getCode());
            payWay.setWayType(payChannel.getCode());
            payWay.setWay(payChannel.getName());
            payWay.setIsPitchOn(EnableDisableStatus.ENABLE.getCode());
            return payWay;
        })).collect(Collectors.toList());

        List<PayWay> payWays = payWayRepository.findAll();
        payWays.forEach(payWay -> payWayList.stream().filter(p -> p.getPayType().equals(payWay.getPayType()) && p.getWayType().equals(payWay.getWayType())).findFirst().ifPresent(p -> payWay.setWay(p.getWay())));

        payWays.addAll(payWayList.stream().filter(p -> payWays.stream().noneMatch(payWay -> payWay.getPayType().equals(p.getPayType()) && payWay.getWayType().equals(p.getWayType()))).collect(Collectors.toList()));
        payWayRepository.saveAll(payWays);
    }

    /**
     * 电子合同参数
     */
    private void initContractParam() {
        if(countTable("cf_contract_param") > 0) {
            return;
        }

        alterSequence("cf_contract_param_seq");

        List<ContractParam> paramList = new ArrayList<>();
        ContractParam param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("甲方(采购方)");
        param.setName("buyerName");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("甲方(供应方)");
        param.setName("supplierName");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("联系人(甲方)");
        param.setName("buyerContractName");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("联系电话(甲方)");
        param.setName("buyerContractMobile");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("收货地址(甲方)");
        param.setName("buyerReceiveAddress");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("开户行(乙方)");
        param.setName("supplierBank");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("开户名(乙方)");
        param.setName("supplierAccount");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("银行账号(乙方)");
        param.setName("supplierCardNo");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("代表人(甲方)");
        param.setName("buyerRepName");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("地址(甲方)");
        param.setName("buyerAddress");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("电话(甲方)");
        param.setName("buyerMobile");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("代表人(乙方)");
        param.setName("supplierRepName");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("地址(乙方)");
        param.setName("supplierAddress");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("电话(乙方)");
        param.setName("supplierMobile");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("商品信息");
        param.setName("goods");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("品牌");
        param.setName("brand");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("产品名称");
        param.setName("product");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("规格");
        param.setName("model");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("数量");
        param.setName("count");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("单价");
        param.setName("price");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("金额");
        param.setName("amount");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("合计");
        param.setName("total");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("备注");
        param.setName("remark");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("商品金额合计(大写)");
        param.setName("productAmountWord");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("运输费金额合计(大写)");
        param.setName("freightAmountWord");
        param.setState(1);
        paramList.add(param);

        param = new ContractParam();
        param.setCreateTime(System.currentTimeMillis());
        param.setDescription("订单总额合计(大写)");
        param.setName("totalAmountWord");
        param.setState(1);
        paramList.add(param);

        contractParamRepository.saveAll(paramList);
    }

    /**
     * 查询表行数
     * @param dbTableName 数据库表名称
     * @return 表行数
     */
    private long countTable(String dbTableName) {
        String sql = "select count(id) as total from " + dbTableName + ";";
        SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql);
        long total = 0;
        while (sqlRowSet.next()) {
            total = sqlRowSet.getLong("total");
        }
        return total;
    }

    /**
     * 将序列值重置为1
     * @param sequenceName 序列名称
     */
    private void alterSequence(String sequenceName) {
        String sql = "alter sequence " + sequenceName + " increment 1 restart with 1";
        jdbcTemplate.execute(sql);
    }
}
